<template>
    <div ref="chartRef" style="width: 100%; height: 400px;"></div>
</template>

<script setup>
import { onMounted, ref, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'


const props = defineProps({
  userAction: { type: Array, default: () => [] },
  xLabels: { type: Array, default: () => [] }
})

const chartRef = ref(null)
let chartInstance = null
let resizeObserver = null

function renderChart() {
  if (!chartInstance) return
  chartInstance.setOption({
    title: {
      text: '题目月数量',
      left: 'center',
      top: 20,
    },
    xAxis: {
      type: 'category',
      data: props.xLabels
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        data: props.userAction,
        type: 'line',
        smooth: true
      }
    ]
  })
}

onMounted(() => {
  chartInstance = echarts.init(chartRef.value)
  renderChart()
  window.addEventListener('resize', () => chartInstance && chartInstance.resize())
  resizeObserver = new ResizeObserver(() => chartInstance && chartInstance.resize())
  resizeObserver.observe(chartRef.value)
})


watch([() => props.userAction, () => props.xLabels], renderChart)

onBeforeUnmount(() => {
  window.removeEventListener('resize', () => chartInstance && chartInstance.resize())
  if (resizeObserver && chartRef.value) {
    resizeObserver.unobserve(chartRef.value)
    resizeObserver.disconnect()
  }
  if (chartInstance) {
    chartInstance.dispose()
  }
})
</script>